<template>
    <div class="vehicle-dashboard">
        <!-- 实时车辆总数 -->
        <div class="vehicle-count-header">
            <div class="count-title">实时车辆</div>
            <div class="count-value">{{ total }}</div>
        </div>

        <!-- 排放阶段进度条 -->
        <div class="back">
            <div class="count-title">排放阶段</div>
            <div class="vehicle-progress-container">
                <div class="progress-item" v-for="(item, index) in vehicleData" :key="index">
                    <div class="progress-header">
                        <span class="rank" style="flex: 1;">No{{ index + 1 }}.</span>
                        <span class="category" style="flex: 1;">{{ item.name }}</span>
                        <!-- <span class="count" style="flex: 1;">{{ item.value }}辆 {{item.percentage + "%" }}</span> -->
                        <span class="count" style="flex: 1;">{{ item.percentage + "%" }}</span>

                    </div>
                    <div class="progress-bar-container">
                        <!-- 通过item.standard动态匹配颜色 -->
                        <div class="progress-bar" :style="{
                            width: item.percentage + '%',
                            backgroundColor: getColorByStandard(item.name)
                        }">
                            <div class="progress-animation"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <!-- 饼图 -->
        <div class="back">
            <div class="count-title">能源类型</div>
            <div id="pieChart" style="width: 400px; height: 300px; margin-top: 20px;"></div>
        </div>
    </div>
</template>

<script>
import * as echarts from 'echarts';
import { analysisRegionVehicle } from '@/api/largescreen'
import { mapState } from "vuex";

export default {
    props: {
        total: {
            type: Number,
            default: 0
        },
    },

    data() {
        return {
            Colors: {
                '国三': '#f95454',
                '国四': '#ff9500',
                '国五': '#d4e607',
                '国六': '#07e7f3',
                '新能源': '#07e6ac',
            },
            totalVehicles: 0, // 实时车辆总数
            totalVehicles_: 0,
            vehicleData: [
                // { name: '国六', value: 1412, percentage: 31 },
                // { name: '国五', value: 2617, percentage: 58 },
                // { name: '国四及以下', value: 70, percentage: 2 },
                // { name: '新能源', value: 440, percentage: 9 }
            ],
            // 饼图数据 - 新能源、天然气、柴油车
            pieChartData: [
                // { value: 440, name: '新能源' },
                // { value: 303, name: '天然气' },
                // { value: 3796, name: '柴油车' }
            ]
        };
    },
    mounted() {

    },
    watch: {
        dataScope: {
            immediate: false,
            deep: true,
            handler(newValue, oldValue) {
                analysisRegionVehicle(this.searchRegion).then((res) => {
                    let data = res.data
                    let vehicle = []
                    vehicle.push({ name: '新能源', value: data.xnyVehicleNum, percentage: ((data.xnyVehicleNum / data.vehicleNum) * 100).toFixed(1) })
                    vehicle.push({ name: '国六', value: data.g6VehicleNum, percentage: ((data.g6VehicleNum / data.vehicleNum) * 100).toFixed(1) })
                    vehicle.push({ name: '国五', value: data.g5VehicleNum, percentage: ((data.g5VehicleNum / data.vehicleNum) * 100).toFixed(1) })
                    vehicle.push({ name: '国四', value: data.g4VehicleNum, percentage: ((data.g4VehicleNum / data.vehicleNum) * 100).toFixed(1) })
                    vehicle.push({ name: '国三', value: data.g3VehicleNum, percentage: ((data.g3VehicleNum / data.vehicleNum) * 100).toFixed(1) })

                    this.vehicleData = vehicle
                    let pieChart = []
                    pieChart.push({ name: '新能源', value: data.xnyVehicleNum })
                    pieChart.push({ name: '天然气', value: data.naturalGasVehicleNum })
                    pieChart.push({ name: '柴油车', value: data.dieselVehicleNum })

                    this.pieChartData = pieChart
                    this.initBarChart()
                    this.initPieChart();

                })
            }
        }
    },
    computed: {
        ...mapState({
            dataScope: (state) => state.map.DataScope,
        }),

        searchRegion() {
            if (this.dataScope.region == 'qz') {
                return {}
            } else {
                let res = this.dataScope.options.find(v => v.value == this.dataScope.region)
                return { regionName: res.label, regionId: res.value };
            }
        },
    },
    methods: {
        getColorByStandard(standard) {
            return this.Colors[standard] || '#000'; // 默认黑色
        },
        initBarChart() {
            this.vehicleData = this.vehicleData.sort((a, b) => b.value - a.value)
        },
        initPieChart() {
            const pieChartDom = document.getElementById('pieChart');
            const myPieChart = echarts.init(pieChartDom);

            const optionPie = {
                backgroundColor: 'transparent', // 透明背景

                legend: {
                    orient: 'vertical',
                    right: 10,
                    textStyle: {
                        color: '#FFFFFF'
                    }
                },
                series: [
                    {
                        name: '车辆类型',
                        type: 'pie',
                        data: this.pieChartData,
                        radius: ['30%', '60%'],
                        center: ['50%', '60%'],
                        label: {
                            // position: 'outside', // 固定在外侧
                            avoidLabelOverlap: true, // 启用标签避挤
                            // ... 其他配置
                            overflow: 'break', // 文本自动换行（需配合 formatter 手动换行）
                            textStyle: {
                                color: '#FFFFFF'
                            },
                            // formatter: '{b}: {c} ({d}%)',
                            formatter: '{b}:  ({d}%)',

                        },
                        itemStyle: {
                            borderWidth: 1,
                            borderColor: 'transparent'
                        },

                        color: [
                            '#7B61FF',  // 新能源 - 紫色
                            '#00B42A',  // 天然气 - 绿色
                            '#FF7D00'   // 柴油车 - 橙色
                        ]
                    }
                ]
            };

            myPieChart.setOption(optionPie);
        },

        // 实时车辆数字动画效果
        startCountAnimation() {
            let currentCount = 0;
            const targetCount = this.totalVehicles;
            const duration = 2000; // 2秒动画时长
            const interval = 50; // 50ms更新一次
            const steps = duration / interval;
            const increment = targetCount / steps;

            const timer = setInterval(() => {
                currentCount += increment;
                if (currentCount >= targetCount) {
                    currentCount = targetCount;
                    clearInterval(timer);
                }
                this.totalVehicles_ = Math.floor(currentCount);
            }, interval);
        }
    }
};
</script>

<style scoped>
.back {

    background-color: rgba(56, 68, 92, 0.7);
    /* 半透明背景 */
    border-radius: 8px;
    padding: 15px 20px;
    margin-bottom: 20px;
    text-align: center;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
}

.vehicle-dashboard {
    width: 480px;
    font-family: Arial, sans-serif;
    background-color: transparent;
    /* 透明背景 */
    padding: 20px;
    border-radius: 10px;
}

.vehicle-count-header {
    background-color: rgba(56, 68, 92, 0.7);
    /* 半透明背景 */
    border-radius: 8px;
    padding: 15px 20px;
    margin-bottom: 20px;
    text-align: center;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
}

.count-title {
    font-size: 16px;
    color: #FFFFFF;
    margin-bottom: 5px;
    text-align: center;
}

.count-value {
    font-size: 32px;
    font-weight: bold;
    color: #FFFFFF;
    letter-spacing: 2px;
}

.progress-item {
    margin-bottom: 15px;
}

.progress-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 5px;
    font-weight: bold;
    color: #FFFFFF;
}

.rank {
    color: #FFFFFF;
}

.category {
    color: #FFFFFF;
}

.count {
    color: #FFFFFF;
}

.progress-bar-container {
    height: 25px;
    background-color: rgba(74, 85, 104, 0.7);
    /* 半透明背景 */
    border-radius: 4px;
    overflow: hidden;
    position: relative;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.3) inset;
}

.progress-bar {
    height: 100%;
    border-radius: 4px;
    position: relative;
    overflow: hidden;
    transition: width 1s ease-in-out;
}

/* 不同排放阶段的进度条颜色 */
.progress-item:nth-child(1) .progress-bar {
    background-color: #07e7f3;
}

.progress-item:nth-child(2) .progress-bar {
    background-color: #d4e607;

}

.progress-item:nth-child(3) .progress-bar {
    background-color: #ff9500;
}

.progress-item:nth-child(4) .progress-bar {
    background-color: #f95454;
}

.progress-item:nth-child(5) .progress-bar {
    background-color: #07e6ac;

}

.progress-animation {
    position: absolute;
    top: 0;
    left: 0;
    height: 100%;
    width: 20%;
    background: linear-gradient(to right, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.5) 50%, rgba(255, 255, 255, 0) 100%);
    animation: shine 2s infinite linear;
}

@keyframes shine {
    0% {
        transform: translateX(-100%);
    }

    100% {
        transform: translateX(500%);
    }
}
</style>